<?php

namespace App\Console\Commands\Tools\OpenShop\Contract;

use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Library\Rms\RmsPayApi;
use App\Models\OpenShop\InvestmentPromotion\OpenShopContractTemplateModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderPermissionAnchorModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Service\OpenShop\Feishu\ShopManualService;
use App\Service\OpenShop\OrderService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class RelocationRollback extends Command
{
    protected $signature   = 'tools:open_shop:relocation_rollback {orderNo}';
    protected $description = '迁址回退';

    public function handle()
    {
        $orderNo = $this->argument('orderNo');

        $openShopOrderSign = OpenShopSignOrderModel::query()
                                                   ->where('orderNo', $orderNo)
                                                   ->with([
                                                       'mainProcessRel' => function ($query) {
                                                           return $query->with([
                                                               'childLocationOrdersRel' => function ($query2
                                                               ) {
                                                                   return $query2->with('signOrderRel');
                                                               }
                                                           ]);
                                                       }
                                                   ])
                                                   ->first();


        // 校验是否迁址
        if (empty($openShopOrderSign->mainProcessRel->childLocationOrdersRel)) {
            $this->error('迁址单不存在');
            return;
        }

        DB::beginTransaction();

        try {
            // 关闭迁址订单
            foreach ($openShopOrderSign->mainProcessRel->childLocationOrdersRel as $item) {
                $item->childLocationOrder = 0;
                $item->locationPid        = 0;
                $item->save();

                $item->signOrderRel->status = SignOrderEnum::ORDER_STATUS_NO;
                $item->signOrderRel->save();
            }

            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            dd($exception);
        }

        $this->info('订单已回退迁址');

    }
}
